package com.kin207.netty;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.Executors;

import com.kin207.netty.handle.MessageHandles;

public class TcpClient {

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		int port = args.length==1?Integer.parseInt(args[0]):8379;
		port = args.length>1?Integer.parseInt(args[1]):8379;
		String ip = args.length>1?args[0]:"127.0.0.1";
		System.out.println("conntion "+ip+":"+port+"...");
		
		final Socket socket = new Socket(ip, port);
		MessageHandles.printHandles();
		
		Executors.newSingleThreadExecutor().submit(new Runnable() {
			public void run() {
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
					String msg = null;
					while((msg=br.readLine())!=null){
						System.out.println("server:"+msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
			}
		});
		
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		Scanner scann = new Scanner(System.in);
		while(true){
			String msg = scann.nextLine();
			bw.write(msg+"\n");
			bw.flush();
		}
	}

}
